package com.alibaba.citrus.cr.mn.order.center.facade.adapter.impl;

import com.alibaba.citrus.cr.mn.order.center.common.enums.CustomerCenterConfigEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.CustomerCenterAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.CostCenterDTO;
import com.alibaba.cloud.retail.customer.center.ability.ActualSalesOrgAbilityService;
import com.alibaba.cloud.retail.customer.center.ability.ConfigurationAbilityService;
import com.alibaba.cloud.retail.customer.center.ability.CostCenterAbilityService;
import com.alibaba.cloud.retail.customer.center.req.QueryActualSalesOrgReq;
import com.alibaba.cloud.retail.customer.center.req.configuration.ConfigurationOptionReq;
import com.alibaba.cloud.retail.customer.center.resp.ActualSalesOrgListResp;
import com.alibaba.cloud.retail.customer.center.resp.CostResp;
import com.alibaba.cloud.retail.customer.center.resp.option.ConfigurationOptionResp;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lydass.bizphin.maca.model.Result;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author dongju
 * @ClassName CustomerCenterAdapterImpl
 * @description: 成本中心适配器
 * @date 2023/06/14
 * @version: 1.0
 */
@Service
public class CustomerCenterAdapterImpl implements CustomerCenterAdapter {
    private static final Log log = Log.getLogger(CustomerCenterAdapterImpl.class);

    @DubboReference
    private CostCenterAbilityService costCenterAbilityService;
    @DubboReference
    private ConfigurationAbilityService configurationAbilityService;
    @DubboReference
    private ActualSalesOrgAbilityService actualSalesOrgAbilityService;

    @Override
    public List<CostCenterDTO> queryCostCenter(List<String> costCenterCodeList) {
        if (CollectionUtils.isEmpty(costCenterCodeList)) {
            return Lists.newArrayList();
        }

        try {
            Result<List<CostResp>> listResult = costCenterAbilityService.queryCostCenter(costCenterCodeList);
            log.info("CustomerCenterAdapterImpl#queryCostCenter listResult: {}", JSON.toJSONString(listResult));
            if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
                return Lists.newArrayList();
            }
            return listResult.getResult().stream().map(cost -> {
                CostCenterDTO costCenterDTO = new CostCenterDTO();
                BeanUtils.copyProperties(cost, costCenterDTO);
                return costCenterDTO;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.info("CustomerCenterAdapterImpl#queryCostCenter error", e);
        }
        return Lists.newArrayList();
    }

    public Map<String, String> queryCustomerGroup() {
        try {
            ConfigurationOptionReq request = new ConfigurationOptionReq();
            request.setType(CustomerCenterConfigEnum.CUSTOMER_GROUP.getCode());
            List<ConfigurationOptionResp> result = this.doQueryConfigurationOptionList(request);
            log.info("销售组查询 request={} result={}", JSON.toJSONString(request), JSON.toJSONString(result));
            return result.stream().collect(Collectors.toMap(ConfigurationOptionResp::getValue, ConfigurationOptionResp::getName));
        } catch (Exception e) {
            log.info("CustomerCenterAdapterImpl#queryCustomerGroup error", e);
        }
        return Maps.newHashMap();
    }

    public Map<String, String> querySalesOrganization(List<String> codeList) {
        if (CollectionUtils.isEmpty(codeList)) {
            return Maps.newHashMap();
        }
        try {
            QueryActualSalesOrgReq request = new QueryActualSalesOrgReq();
            request.setOrgCodeList(codeList);
            Result<List<ActualSalesOrgListResp>> result = actualSalesOrgAbilityService.getActualSalesOrgList(request);
            log.info("销售组织查询 request={} result={}", JSON.toJSONString(request), JSON.toJSONString(result));
            if (Objects.isNull(result) || CollectionUtils.isEmpty(result.getResult())) {
                return Maps.newHashMap();
            }
            return result.getResult().stream().collect(Collectors.toMap(ActualSalesOrgListResp::getOrgCode, ActualSalesOrgListResp::getSalesOrgName));
        } catch (Exception e) {
            log.info("CustomerCenterAdapterImpl#querySalesOrganization error", e);
        }
        return Maps.newHashMap();
    }

    public Map<String, String> querySalesDepartment(List<String> codeList) {
        if (CollectionUtils.isEmpty(codeList)) {
            return Maps.newHashMap();
        }
        try {
            ConfigurationOptionReq request = new ConfigurationOptionReq();
            request.setType(CustomerCenterConfigEnum.SALES_GROUP.getCode());
            request.setCodeList(codeList);
            List<ConfigurationOptionResp> result = this.doQueryConfigurationOptionList(request);
            log.info("销售部门查询 request={} result={}", JSON.toJSONString(request), JSON.toJSONString(result));
            return result.stream().collect(Collectors.toMap(ConfigurationOptionResp::getValue, ConfigurationOptionResp::getName));
        } catch (Exception e) {
            log.info("CustomerCenterAdapterImpl#querySalesDepartment error", e);
        }
        return Maps.newHashMap();
    }

    public Map<String, String> querySalesChannel(List<String> codeList) {
        if (CollectionUtils.isEmpty(codeList)) {
            return Maps.newHashMap();
        }
        try {
            ConfigurationOptionReq request = new ConfigurationOptionReq();
            request.setType(CustomerCenterConfigEnum.SALES_OFFICE.getCode());
            request.setCodeList(codeList);
            List<ConfigurationOptionResp> result = this.doQueryConfigurationOptionList(request);
            log.info("销售渠道查询 request={} result={}", JSON.toJSONString(request), JSON.toJSONString(result));
            return result.stream().collect(Collectors.toMap(ConfigurationOptionResp::getValue, ConfigurationOptionResp::getName));
        } catch (Exception e) {
            log.info("CustomerCenterAdapterImpl#querySalesChannel error", e);
        }
        return Maps.newHashMap();
    }

    private List<ConfigurationOptionResp> doQueryConfigurationOptionList(ConfigurationOptionReq configurationOptionReq) {
        try {
            int page = 1;
            int size = 100;
            configurationOptionReq.setSize(size); // 最大支持100条
            configurationOptionReq.setPermission(false); // 页面权限控制入参，默认传false，防止数据缺失

            List<ConfigurationOptionResp> respList = new ArrayList<>();
            while (true) {
                configurationOptionReq.setPage(page++);
                Result<List<ConfigurationOptionResp>> listResult = configurationAbilityService.queryConfigurationOptionList(configurationOptionReq);
                if (Objects.isNull(listResult)) {
                    break;
                }
                respList.addAll(listResult.getResult());
                if (CollectionUtils.isEmpty(listResult.getResult()) || listResult.getResult().size() < size) {
                    break;
                }
            }

            return respList;
        } catch (Exception e) {
            log.info("CustomerCenterAdapterImpl#doCallQueryConfigurationOptionList error", e);
        }
        return Lists.newArrayList();
    }
}
